package tool

import (
	"encoding/json"
	"kingbloc.dts/models"
	"kingbloc.sso/user"
	"kingbloc.util/util"
	"net/url"
	"os"
	"strconv"
)

var currentWd string

func init() {
	currentWd, _ = os.Getwd()
}

func RegDB(dbtype, url, name, pwd, isShow string) {
	model.GetMysqlEngine(dbtype, url, name, pwd, isShow)
}

var Conf *util.Config = nil

func SetConfigPath(filepath string) *util.Config {
	if Conf != nil {
		return Conf
	}
	Conf = new(util.Config)
	Conf.Filepath = filepath
	return Conf
}

func GetConfig() *util.Config {
	return Conf
}

func UserByToken(token string) *user.User {
	// 该手机号是否有报过单
	conf := GetConfig()
	ssoUrl := conf.Get("sso", "url")
	ssoUrl += "/find"
	param := url.Values{}
	param.Set("k", "token")
	param.Set("v", token)
	data, _ := util.Post(ssoUrl, param)

	if len(data) > 0 {
		user := new(user.User)
		json.Unmarshal(data, user)
		return user

	}
	return nil

}

func InitTables() {

	model.MysqlEngine.DropTables(new(model.Orderr), new(model.Account), new(model.Today))
	model.MysqlEngine.CreateTables(new(model.Orderr), new(model.Account), new(model.Today))
	model.MysqlEngine.Sync2(new(model.Orderr), new(model.Account), new(model.Today))
	//
	model.MysqlEngine.DropTables(new(model.LayerAward), new(model.AmountAward), new(model.LuckyAward), new(model.ManagementAward), new(model.CharmAward))
	model.MysqlEngine.CreateTables(new(model.LayerAward), new(model.AmountAward), new(model.LuckyAward), new(model.ManagementAward), new(model.CharmAward))
	model.MysqlEngine.Sync2(new(model.LayerAward), new(model.AmountAward), new(model.LuckyAward), new(model.ManagementAward), new(model.CharmAward))
	//
}

func UserInfoByMob(mob string) *user.User {

	// 该手机号是否有报过单
	conf := GetConfig()
	ssoUrl := conf.Get("sso", "url")
	ssoUrl += "/find"
	param := url.Values{}
	param.Set("k", "mob")
	param.Set("v", mob)
	data, _ := util.Post(ssoUrl, param)

	if len(data) > 0 {
		user := new(user.User)
		json.Unmarshal(data, user)
		return user

	}
	return nil

}

func UserInfoById(ssoid int64) *user.User {
	userid := strconv.FormatInt(ssoid, 10)
	return UserInfoByIdStr(userid)
}

func UserInfoByIdStr(ssoid string) *user.User {

	// 该手机号是否有报过单
	conf := GetConfig()
	ssoUrl := conf.Get("sso", "url")
	ssoUrl += "/find"
	param := url.Values{}
	param.Set("k", "id")
	param.Set("v", ssoid)
	data, _ := util.Post(ssoUrl, param)

	if len(data) > 0 {
		user := new(user.User)
		json.Unmarshal(data, user)
		return user

	}
	return nil

}
